<!-- 发布悬赏/编辑 -->
<template>
	<!-- 步骤 -->
	<view class="steps">
		<steps :list="data.steps" :active="4" activePointColor="#aaa" activeLineColor="#ddd" activeTextColor="#222" activeDescColor="#aaa" />
	</view>
	<!-- 联系 -->
	<view class="contact">
		<view class="msg"><text>不会填？填不好？我们帮助你填 →</text></view>
		<button type="default" class="btn" hover-class="btnClickStyle" @click.stop="contact()">联系客服</button>
	</view>
	<!-- 表单提交 -->
	<form class="form" @submit="sub">
		<view class="form-item">
			<view class="form-title">
				<view class="label"><text class="red">*</text>悬赏标题</view>
				<view class="value">{{data.formData.title.length}}/50</view>
			</view>
			<view class="form-control">
				<input class="input" type="text" maxlength="50" v-model="data.formData.title" name="title" placeholder="例如:我要制作一个PPT" placeholder-class="placeholderStyle">
			</view>
		</view>
		<view class="form-item">
			<view class="form-title">
				<view class="label"><text class="red">*</text>详细描述</view>
				<view class="value">{{data.formData.description.length}}/1000</view>
			</view>
			<view class="form-control">
				<textarea class="textarea" maxlength="1000" v-model="data.formData.description" :disabled="data.textareaDis" name="description" placeholder="例如：我有现成的内容，只需要排版设计。金融行业，用于项目融资介绍。具体可联系我详谈" placeholder-class="placeholderStyle"></textarea>
			</view>
		</view>
		<view class="form-item">
			<view class="form-title">
				<view class="label"><text class="red">*</text>预算（元）</view>
				<view class="value" v-if="!data.priceIsRange">当前是确切值，可切换为 <text class="red toogle" @click="toogle()">区间值</text></view>
				<view class="value" v-else>当前是区间值，可切换为 <text class="red toogle" @click="toogle()">确切值</text></view>
			</view>
			<view class="form-control">
				<template v-if="!data.priceIsRange">
					<input class="input" type="number" maxlength="50" v-model="data.formData.price" name="price" placeholder="请填写大于0的数字" placeholder-class="placeholderStyle" @blur="changePrice($event,'price')">
				</template>
				<template v-else>
					<input class="input" type="number" maxlength="50" v-model="data.formData.price_start" name="price_start" placeholder="最低" placeholder-class="placeholderStyle" @blur="changePrice($event,'price_start')">
					<text class="line"></text>
					<input class="input" type="number" maxlength="50" v-model="data.formData.price_end" name="price_end" placeholder="最高" placeholder-class="placeholderStyle" @blur="changePrice($event,'price_end')">
				</template>
			</view>
		</view>
		<view class="form-item">
		</view>
		<view class="form-item">
			<view class="form-title">
				<view class="view"><text class="red">*</text>截止日期</view>
			</view>
			<view class="form-control">
				<input type="text" class="input time" v-model="data.formData.deadline" name="deadline" placeholder="点击选择" placeholder-style="color:#666;" disabled>
				<uni-datetime-picker type="date" :value="data.datetime.value" :start="data.datetime.start" :end="data.datetime.end" placeholder="Ceshi" @change="changeTime" @close="closeTime" @show="showTime" />
				<icon class="iconfont icon">&#xe7d3;</icon>
			</view>
		</view>
		<view class="form-submit">
			<view class="agreement" v-if="data.options&&data.options.type!='edit'">
				<text>提交即表示已阅读并同意</text>
				<navigator class="nav" :url="agreementUrl">悬赏发布及接单须知</navigator>
			</view>
			<template v-if="$store.getters.token||!isEmptyFormData">
				<button form-type="submit" :class="['btn btn-sub',{'btn-dis':!isEmptyFormData}]" hover-class="btnClickStyle">{{data.options&&data.options.type=='edit'?'确认修改':'提交'}}</button>
			</template>
			<template v-else>
				<button class="btn btn-sub" hover-class="btnClickStyle" @click="navToCheckLogin">{{data.options&&data.options.type=='edit'?'确认修改':'提交'}}</button>
			</template>
		</view>
	</form>
	<!-- 登录组件 -->
	<weixin-login ref="wxLogin" />
	<!-- 联系客服 -->
	<popup-contact ref="popupContactRef" />
</template>
<script setup>
	import { ref, reactive, computed, defineComponent, getCurrentInstance } from 'vue';
	import { onLoad } from '@dcloudio/uni-app';
	import { valid } from '@/subpages/common/utils/valid.js';
	import { addTask, updateTask } from '@/subpages/common/api/task/edit.js';
	import { checkBindAccount } from '@/common/api/user.js';
	import config from '@/uni.config.js';
	import { isEmpty } from '@/common/utils/index.js';
	import useStatus from '@/common/hooks/useStatus.js';
	import { showModal } from '@/common/hooks/useShow.js';
	import popupContact from "./components/popup-contact.vue";
	const wxLogin = ref(null);
	const popupContactRef = ref(null);
	const { navToCheckLogin } = useStatus(wxLogin);
	defineComponent({
		popupContact
	});
	onLoad((options) => {
		data.options = options;
		init();
		const instance = getCurrentInstance().proxy;
		eventChannel = instance.getOpenerEventChannel();
	});
	let eventChannel = null;
	const isEmptyFormData = computed(() => {
		return !isEmpty(data.formData.title) && !isEmpty(data.formData.description) && !isEmpty(data.formData.deadline) && (!isEmpty(data.formData.price) || (!isEmpty(data.formData.price_start) && !isEmpty(data.formData.price_end)))
	});
	const agreementUrl = computed(() => {
		return `/subpages/web/web?url=${encodeURIComponent(config.article.task)}`
	});
	const data = reactive({
		options: null,
		taskid: '', //任务id
		priceIsRange: false,
		textareaDis: false,
		formData: {
			title: '', //标题
			description: '', //描述
			deadline: '', //截止时间
			price: '', //价格
			price_start: '', //区间价格开始
			price_end: '', //区间价格结束
			task_from: config.title //任务来源
		},
		datetime: {
			start: Date.now(),
			end: Date.now() + 100000000000000,
			value: Date.now()
		},
		steps: [{
			name: '登记',
			desc: '审核发布'
		}, {
			name: '沟通',
			desc: '深入洽谈'
		}, {
			name: '选人',
			desc: '确认接单'
		}, {
			name: '执行',
			desc: '实现需求'
		}, {
			name: '完成',
			desc: '支付报酬'
		}],
	});
	// 初始化
	function init() {
		const options = data.options;
		switch (options.type) {
			case 'edit':
				const item = JSON.parse(decodeURIComponent(options.item));
				const priceArr = item.price.split('-');
				uni.setNavigationBarTitle({
					title: '修改悬赏'
				});
				data.taskid = item.taskid;
				data.priceIsRange = priceArr.length > 1;
				data.formData.title = item.title;
				data.formData.description = item.description;
				data.formData.deadline = item.deadline;
				data.formData.price = priceArr.length > 1 ? '' : item.price;
				data.formData.price_start = priceArr.length > 1 ? priceArr[0] : '';
				data.formData.price_end = priceArr.length > 1 ? priceArr[1] : '';
				break;
			default:
				uni.setNavigationBarTitle({
					title: '发布悬赏'
				});
				break;
		}
	}
	// 价格处理
	function changePrice(e, type) {
		const value = (+e.detail.value);
		if (value >= 0 && (e.detail.value + '') != '' && /[.]/.test(value)) data.formData[type] = value.toFixed(2);
	}
	// 确切值和区间值的切换
	function toogle() {
		data.priceIsRange = !data.priceIsRange;
	}
	// 选择时间
	function changeTime(e) {
		data.formData.deadline = e;
	}
	// 显示时间选择器
	function showTime() {
		data.textareaDis = true;
	}
	// 关闭时间选择器
	function closeTime() {
		data.textareaDis = false;
	}
	// 提交
	async function sub(e) {
		let subData = e.detail.value;
		let rules = [{
			value: subData.title,
			null: '请填写悬赏标题（5-50个字）',
			dataType: '5&50',
			error: '请填写悬赏标题（5-50个字）'
		}, {
			value: subData.description,
			null: '请填写详细描述（10-1000个字）',
			dataType: '10&1000',
			error: '请填写详细描述（10-1000个字）'
		}];
		if (data.priceIsRange) { //是价格区间
			rules.push({
				value: subData.price_start,
				null: '预算请填写0-100000的数字',
				dataType: '0-100000',
				error: '预算请填写0-100000的数字'
			}, {
				value: subData.price_end,
				null: '预算请填写0-100000的数字',
				dataType: '0-100000',
				error: '预算请填写0-100000的数字'
			})
		} else {
			rules.push({
				value: subData.price,
				null: '预算请填写0-100000的数字',
				dataType: '0-100000',
				error: '预算请填写0-100000的数字'
			})
		}
		rules.push({
			value: subData.deadline,
			null: '请选择截止日期'
		})
		const dataTypes = { dataTypes: { '5&50': /^[\w\W]{5,50}$/, '10&1000': /^[\w\W]{10,1000}$/, 'lg0': /^([1-9]\d*)(\.\d{1,6})?$|^0\.\d{1,6}?$/, '0-100000': /(^(0|[1-9]|[1-9][0-9]{1,4})(\.\d{1,2})?$)|(^100000$)/ }, tip: 1 };
		valid(rules, dataTypes).then(res => {
			if (data.priceIsRange) {
				if (+subData.price_start >= +subData.price_end) return uni.showToast({
					icon: 'none',
					title: '预算区间值最低不能大于或等于最高'
				})
				subData.price = `${subData.price_start}-${subData.price_end}`;
				delete subData.price_start;
				delete subData.price_end;
			}
			subData.deadline = parseInt(Date.parse(`${subData.deadline} 23:59:59`) / 1000);
			subData.task_from = data.formData.task_from;
			subReq(subData);
		})
	}
	// 提交请求
	async function subReq(params) {
		switch (data.options.type) {
			case 'edit':
				params.taskid = data.taskid;
				await updateTask(params);
				eventChannel.emit('acceptDataFromOpenedPage', { type: 'edit', value: 1 });
				setTimeout(() => {
					uni.navigateBack();
				}, 600)
				break;
			default:
				await addTask(params);
				setTimeout(async () => {
					switch (data.options.from) {
						case 'task':
							uni.redirectTo({
								url: '/subpages/user-consumer/task-list/task-list'
							})
							const isPbulicRes = await checkBindAccount();
							if (isPbulicRes.data.is_show_subscribe == 1) setTimeout(() => {
								showModal({
									title: '关注公众号',
									content: '消息是通过微信公众号通知的哦~ 不关注的话，可能错过悬赏进展与动态',
									confirmText: '去关注',
									confirm() {
										uni.navigateTo({
											url: `/subpages/web/web?url=${encodeURIComponent(config.article.public)}`
										})
									}
								})
							}, 500)
							break;
						default:
							eventChannel.emit('acceptDataFromOpenedPage', { type: 'addTask' });
							uni.navigateBack();
							break;
					}
				}, 600)
				break;
		}
	}
	// 联系客服
	function contact() {
		popupContactRef.value.open();
	}
</script>
<style lang="scss">
	@import '@/common/css/base.scss';
	page {
		padding-bottom: 180rpx;
		background-color: $bgColor;
	}
	.uni-date-editor--x {
		opacity: 0 !important;
	}
</style>
<style scoped lang="scss">
	@import '@/common/css/base.scss';
	@import '@/common/css/form.scss';
	.steps {
		padding: 20rpx 0;
		background-color: #fff;
	}
	.contact {
		@include flex;
		height: 72rpx;
		padding: 0 32rpx;
		background: #FFF5E5;
		font-size: 22rpx;
		color: $color;
		.btn {
			width: 124rpx;
			height: 44rpx;
			line-height: 40rpx;
			margin: 0;
			padding: 0;
			border: 2rpx solid $color;
			border-radius: 6rpx;
			background: #FFF5E5;
			text-align: center;
			font-size: 22rpx;
			color: $color;
		}
	}
</style>
